/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.config;

import java.util.HashMap;
import org.apache.struts.action.ActionForward;

/**
 * @author
 * Walter
 * L�tgenau
 */
public class NavigationConfig {
    HashMap<String, HashMap<String, String>> navigations = new HashMap<String, HashMap<String, String>>();
    
    /**
     * Add navigations to the configuration. The navigations are a map of page navigations.
     * If the page is already configured, add page navigations to it, else add the page navigation 
     * completely.
     * 
     * @param navigationItems 
     */
    public void addNavigations(HashMap<String, HashMap<String, String>> navigationItems) {
        for (String page : navigationItems.keySet()) {
            if (navigations.containsKey(page)) { // add navigations to the page
                HashMap<String, String> pageNavigations = navigations.get(page);
                for (String  key : navigationItems.get(page).keySet()) {
                    pageNavigations.put(key, navigationItems.get(page).get(key));
                }                    
            } else
                navigations.put(page, navigationItems.get(page));
        }
    }
    
    /**
     * Return a struts ActionForward. 
     * 
     * @param action the struts action
     * @param name the name of the forward.
     * @return the forward
     */
    public ActionForward getActionForward(String action, String name) {
        final String DELIMITER = ":";
        
        HashMap<String, String> actionForwards = navigations.get(action);
        if (actionForwards == null)
            return null;
        
        String actionForward = actionForwards.get(name);
        if (actionForward == null)
            return null;
        
        String path = actionForward;
        boolean redirect = false;
        
        if (actionForward.indexOf(DELIMITER) >= 0) {
            String[] components = actionForward.split(DELIMITER);
            path = components[0];
            redirect = Boolean.valueOf(components[1]).booleanValue();
        }
        
        return new ActionForward(name, path, redirect);
    }
}
